import { defineStore } from 'pinia'
import UserService from '@/service/user'
import { HttpStatusCode } from '@/utils/constant'
import { UserLoginVo } from '@/service/user/vo'

// const [token, setToken] = useLocalStorageState('token', {
//   defaultValue: '',
// })

const useUserStore = defineStore('User', {
  state: () => {
    return {
      token: '',
      username: '',
      avatar: '',
    }
  },
  actions: {
    /**
     * 用户登录
     * @param p
     */
    async userLogin(p: UserLoginVo) {
      const res = await UserService.login(p)
      const resToken = res.data?.token
      if (res.code === HttpStatusCode.Ok) {
        // 登录成功，保存token到本地
        localStorage.setItem('token', resToken)
        return 'ok'
      }
      return Promise.reject(new Error(res.msg))
    },
    /**
     * 用户详情
     */
    async uerInfo() {
      const res = await UserService.info()
      if (res.code === HttpStatusCode.Ok) {
        this.username = res.data.username
        this.avatar = res.data.avatar
        return 'ok'
      } else {
        return Promise.reject('获取用户信息失败')
      }
    },
    /**
     * 用户退出登录
     */
    async userLogout() {
      // 需要调接口告诉服务器删除当前session
      this.username = ''
      this.token = ''
      this.avatar = ''
      localStorage.removeItem('token')
    },
  },
})

export default useUserStore
